import React, { Component } from 'react';
import styles from './index.module.scss';
import { connect } from 'react-redux';
import { withConsumer } from '../../context';
import Markdown from 'markdown-to-jsx';
import { LoaderIcon, Terminal } from 'lucide-react';
import classNames from 'classnames';
import { update } from '@/utils/immutableUtil';
import { CodeView } from '@/components/basicComp/CodeView';
import { useState, useEffect, forwardRef } from 'react';
import { useTheme } from 'next-themes';
import { useRouter } from 'next/router';
import { toast } from '@/components/basicComp/Toast';
import Image from 'next/image';
import { motion } from 'framer-motion';
import ConfirmDialog from '@/components/basicComp/Confirm';
import { delMsgItem } from '@/api/ai';
import ToolsItem from './ToolsItem';
import PptOutline from './PptOutline';

// 计算单双数
var isEven = (number) => {
  return number % 2 === 0;
};

const ThemeStyle = () => {
  const { theme } = useTheme();
  const router = useRouter();

  var base = '';
  if (router.basePath) {
    base = router.basePath;
  }

  useEffect(() => {
    // 创建 link 元素
    const link = document.createElement('link');
    link.rel = 'stylesheet';

    link.href =
      theme === 'dark'
        ? `${base}/lib/github-markdown-css/github-markdown-dark-mini.css`
        : `${base}/lib/github-markdown-css/github-markdown-light-mini.css`; // 根据主题选择样式

    // 添加到 document.head
    document.head.appendChild(link);

    // 清理函数，卸载之前引入的样式
    return () => {
      document.head.removeChild(link);
    };
  }, [theme]);

  return <></>;
};

@withConsumer
@connect(({ ppt, user }) => ({
  messages: ppt.messages,
  user: user.user,
  selectedChat: ppt.selectedChat,
  selectedChatInit: ppt.selectedChatInit,
  chatLoading: ppt.chatLoading,
  itemIndex: ppt.itemIndex,
  currentTab: ppt.currentTab,
  openPreview: ppt.openPreview,
}))
class Comp extends Component {
  state = {
    isOpen: false,
  };
  componentDidMount = async () => {
    const {
      value: { setController },
    } = this.props;
    setController('Chat', this);
  };

  //获取展示内容
  getShowText = (textStr = '') => {
    const {
      value: { changeState, setSidebar },
    } = this.props;
    // 代码段截取符号
    const char = '```';
    // 存放代码段符号下标的数组
    const positions = [0];
    // 获取代码段符号位置
    let pos = textStr.indexOf(char);
    while (pos !== -1) {
      positions.push(pos);
      pos = textStr.indexOf(char, pos + 1);
    }
    const arr = [];
    // 根据代码段符号下标获取代码段
    for (let i = 0; i < positions.length; i++) {
      if (!isEven(i + 1)) {
        const str =
          positions?.length > i + 1
            ? textStr
                .substring(positions[i], positions[i + 1])
                .replace('```', '')
            : textStr.substring(positions[i]).replace('```', '');
        arr.push({
          type: 2,
          num: positions[i],
          message: str,
        });
      }
      if (!isEven(i)) {
        const str = textStr
          .substring(positions[i], positions[i + 1])
          .replace('```', '');
        arr.push({
          type: 1,
          num: positions[i],
          message: str,
        });
      }
    }

    return (
      <div className={classNames([styles.chatrow])}>
        <div className={styles.chatWrap}>
          <div className={styles.chatContent}>
            {arr.map((val) => {
              // 获取第一个回车符的下标
              const nindex = val.message.indexOf('\n');
              // 代码类型
              const codeType =
                val.type == 1 ? val.message.substring(0, nindex) : false;
              // 代码输出
              const codeMessage =
                val.type == 1 && nindex !== -1
                  ? val.message.substring(nindex)
                  : val.message;

              // // md格式
              // if (val.type == 1 && codeType == 'markdown') {
              //   console.log('11111')
              //   return (
              //     <div className={styles.markdownBody + ' markdown-body'}>
              //       <Markdown>
              //         {String(codeMessage).replace(/\n$/, '')}
              //       </Markdown>
              //     </div>
              //   );
              // }

              // 代码格式
              if (val.type == 1) {
                return (
                  <div className={styles.codeView}>
                    <div className={styles.options}>
                      <div className={styles.codeType}>{codeType}</div>
                      <div style={{ display: 'flex' }}>
                        <button
                          className={styles.button1}
                          onClick={async () => {
                            try {
                              await navigator.clipboard.writeText(codeMessage);
                              toast.success('Code copied to clipboard');
                            } catch (err) {
                              toast.error('Failed to copy code');
                            }
                          }}
                        >
                          <i className="iconfont icon-fuzhi" />
                          Copy
                        </button>
                        {codeType == 'html' && (
                          <button
                            className={styles.button1}
                            onClick={async () => {
                              changeState({
                                previewType: 'iframe',
                                openPreview: true,
                                currentTab: 'fragment',
                                fragment: {
                                  code: codeMessage,
                                  file_path: 'index.html',
                                },
                              });

                              setTimeout(() => {
                                setSidebar(false);
                              }, 100);
                            }}
                          >
                            <i className="iconfont icon-yulan" />
                            Preview
                          </button>
                        )}
                      </div>
                    </div>
                    <div className={styles.codeCont}>
                      <CodeView
                        code={codeMessage}
                        lang={codeType || 'javascript'}
                      />
                    </div>
                  </div>
                );
              }

              return (
                <div className={styles.markdownBody + ' markdown-body'}>
                  <motion.div
                    initial={{ opacity: 0 }} // 初始状态：不透明度为 0
                    animate={{ opacity: 1 }} // 动画状态：不透明度为 1
                    transition={{ duration: 2 }} // 动画持续时间为 1 秒
                  >
                    <Markdown>{val.message}</Markdown>
                  </motion.div>
                </div>
              );
            })}
          </div>
        </div>
      </div>
    );
  };

  sandbox = async (fragment = {}, index) => {
    const {
      itemIndex,
      value: { changeState, controller, getSandbox },
    } = this.props;
    var rs = await getSandbox(fragment);
    const result = await rs.json();

    var ind = itemIndex;
    if (index != undefined) {
      ind = index;
    }

    changeState({
      codeResult: result,
    });

    var ChatInput = controller.ChatInput;
    if (ChatInput) {
      ChatInput.setMessage({ result }, ind, false);
    }
  };

  handleRefresh = (item) => {
    // Add refresh logic here
    console.log('Refresh clicked', item);
  };

  handleDelete = async () => {
    const {
      itemIndex,
      value: { changeState, controller, getSandbox },
    } = this.props;

    var item = this.msgItem.itemData;
    var reqData = {
      id: item.id,
      conversation_id: item.conversation_id,
    };

    console.log(reqData);

    var rs = await delMsgItem(reqData);
    if (rs.data?.code == 200) {
      this.delItemDom();
      this.setState({ isOpen: false });
    }
  };

  msgOptions = (item, { i1, i2 }) => {
    const {
      value: { changeState },
    } = this.props;
    const handleCopy = async () => {
      try {
        await navigator.clipboard.writeText(item.text);
        toast.success('Content copied to clipboard');
      } catch (err) {
        toast.error('Failed to copy content');
      }
    };

    return (
      <div className={styles.msgOptions}>
        <i
          className="iconfont icon-fuzhi"
          onClick={handleCopy}
          title="Copy content"
        ></i>
        {/* <i
          className="iconfont icon-shuaxin"
          onClick={() => {
            this.handleRefresh(item);
          }}
          title="Refresh response"
        ></i> */}
        <i
          className="iconfont icon-Delete"
          onClick={() => {
            this.msgItem = {
              ...item,
              i1: i1,
              i2: i2,
            };
            this.setState({ isOpen: true });
          }}
          title="Delete message"
        ></i>
      </div>
    );
  };

  delItemDom = () => {
    const {
      value: { changeState },
    } = this.props;
    const { i1, i2 } = this.msgItem;
    const { messages } = this.props;
    var list = JSON.parse(JSON.stringify(messages));
    list[i1].content.splice(i2, 1);
    changeState({ messages: list });
  };

  shouldComponentUpdate = (np, ns) => update.call(this, np, ns);
  render() {
    const { isOpen } = this.state;
    let { messages, selectedChat, selectedChatInit, chatLoading, currentTab } =
      this.props;
    const {
      openPreview,
      value: { changeState, setSidebar },
    } = this.props;

    if (!selectedChat && selectedChatInit && messages.length === 0) {
      return <div></div>;
    }

    return (
      <div className={styles.container}>
        <ThemeStyle />
        {false ? (
          <div
            className="flex items-center justify-center"
            style={{ height: '100%' }}
          >
            <div className="animate-spin rounded-full h-12 w-12 border-t-2 border-b-2 border-gray-900 dark:border-white"></div>
          </div>
        ) : (
          <div className={styles.compCont} id="chat-container">
            <div
              className={classNames(styles.compContBody, {
                [styles.max800]: !openPreview,
              })}
            >
              {messages.length > 0 && (
                <motion.div
                  initial={{ opacity: 0 }} // 初始状态：不透明度为 0
                  animate={{ opacity: 1 }} // 动画状态：不透明度为 1
                  transition={{ duration: 1 }} // 动画持续时间为 1 秒
                  style={{ height: '100%' }}
                >
                  <div
                    className={styles.chatContainer}
                    id="chat-container-cont"
                  >
                    {messages.map((message, index) => {
                      if (message.initData === true) return null;
                      // if(message.role =='user' && !message.text) return null;
                      if (message.text == 'call plan agent') return null;
                      if (message.text == 'call clarification agent') return null;
                      return (
                        <>
                          {message.tool_calls?.map((item, i) => {
                            return (
                              <ToolsItem
                                parentItem={message}
                                data={item}
                                index={i}
                              />
                            );
                          })}
                          {message.content.length > 0 && (
                            <div
                              className={`${
                                message.role !== 'user'
                                  ? styles.msgItemAi
                                  : styles.msgItemUser
                              }`}
                              key={index}
                            >
                              {message.content.map((content, id) => {
                                if (content.type === 'image') {
                                  return (
                                    <img
                                      key={id}
                                      src={content.image}
                                      alt="fragment"
                                      className="mr-2 inline-block w-12 h-12 object-cover rounded-lg bg-white mb-2"
                                    />
                                  );
                                }
                                if (message.role == 'user') {
                                  return <div>{content.text}</div>;
                                }
                                if (content.type === 'text') {
                                  return (
                                    <div>
                                      {this.getShowText(content.text)}
                                      {(() => {
                                        if (
                                          index == messages.length - 1 &&
                                          id == message.content.length - 1 &&
                                          chatLoading
                                        ) {
                                          return;
                                        }

                                        return (
                                          <>
                                            {!message.object &&
                                              content.text &&
                                              this.msgOptions(content, {
                                                i1: index,
                                                i2: id,
                                              })}
                                          </>
                                        );
                                      })()}
                                    </div>
                                  );
                                }
                              })}

                              {/* 生成代码区域 */}
                              {message.object && (
                                <div
                                  onClick={async () => {
                                    changeState({
                                      previewType: 'e2b',
                                      openPreview: true,
                                      fragment: message.object,
                                      result: message.result,
                                      itemIndex: index,
                                    });

                                    setTimeout(() => {
                                      setSidebar(false);
                                    }, 100);

                                    if (
                                      !message.result &&
                                      currentTab === 'fragment'
                                    ) {
                                      this.sandbox(message.object, index);
                                    }
                                  }}
                                  className={styles.codeItem}
                                >
                                  <div className={styles.codeIcon}>
                                    <i
                                      className="iconfont icon-daima"
                                      style={{ fontSize: '16px' }}
                                    ></i>
                                  </div>
                                  <div className="pl-2 pr-4 flex flex-col">
                                    <span className="font-bold font-sans text-sm text-primary">
                                      {message.object.title}
                                    </span>

                                    <span className="font-sans text-sm text-muted-foreground">
                                      Click to see fragment
                                    </span>
                                  </div>
                                  <div className={styles.openButton}>open</div>
                                </div>
                              )}
                            </div>
                          )}
                        </>
                      );
                    })}

                    {selectedChat && <PptOutline chatId={selectedChat} />}

                    {chatLoading && (
                      <div>
                        <div
                          className="flex items-center gap-1 text-sm text-muted-foreground"
                          style={{
                            height: '30px',
                            overflow: 'hidden',
                            marginBottom: '10px',
                          }}
                        >
                          <Image
                            src={require('./img/icon.png')}
                            alt="Logo"
                            width={20}
                            style={{ marginRight: '2px' }}
                          />
                          {/* <LoaderIcon
                        strokeWidth={2}
                        className="animate-spin w-4 h-4"
                      /> */}

                          <span>Generating...</span>
                        </div>
                      </div>
                    )}
                  </div>
                </motion.div>
              )}
            </div>
          </div>
        )}

        <ConfirmDialog
          isOpen={isOpen}
          title={`Confirmation`}
          message="Are you sure to delete the model? You can continue to configure the model after deletion."
          onCancel={() => {
            this.setState({ isOpen: false });
          }}
          onConfirm={() => {
            this.handleDelete();
          }}
          cancelText="Cancel"
          confirmText="Delete"
        />
      </div>
    );
  }
}

export default Comp;
